local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local ClipText = appdf.req(appdf.EXTERNAL_SRC .. "ClipText")
local HeadSprite = appdf.req(appdf.EXTERNAL_SRC .. "HeadSprite")
local loginCMD = appdf.req(appdf.HEADER_SRC .. "CMD_LogonServer")
local utils = appdf.req(appdf.EXTERNAL_SRC .. "Utils")

--个人信息界面
local UserInfoLayer = class("UserInfoLayer", function(scene)
	local userInfoLayer = display.newLayer()
	return userInfoLayer
end)

local AlipayLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindAlipayLayer')
local BindBankLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.BindBankLayer')
local Bank = appdf.req(appdf.CLIENT_SRC .. "plaza.views.layer.plaza.BankLayer")
local ModifyLayer = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.ModifyNickNameLayer')
local ModifyHead = appdf.req(appdf.CLIENT_SRC .. 'plaza.views.layer.plaza.ChangeHeadLayer')
local Binding = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.plaza.BindingLayer")
local bGender = false

local labColor = cc.c3b(204, 172, 139)

function UserInfoLayer:ctor(scene)
	ExternalFun.registerNodeEvent(self)
	self._scene = scene

	self:loadCSB()
	self:init()
	-- self:setContentSize(yl.WIDTH, yl.HEIGHT)
	
end

function UserInfoLayer:loadCSB()
	local _, root = ExternalFun.loadRootCSB("userinfo/UserInfoLayer.csb", self)
	self.csbNode = root
	-- ExternalFun.FixTopUI(root)
	self.csbNode:setPositionY((display.height-750)/2)
	self.bg = root:getChildByName("bg2_1")
	self.panelLayout = root:getChildByName("panel_layout")
	
	local btnCallback = function(ref, type)
		if type == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect()
			ref:setScale(1)
			self:onButtonClicked(ref:getTag(), ref)
		elseif type == ccui.TouchEventType.began then
			ref:setScale(yl.btscale)
			return true
		elseif type == ccui.TouchEventType.canceled then
			ref:setScale(1)
		end
	end
	local pl = self.panelLayout
	ExternalFun.FixScaleUI(pl)
	
	self.tf_nick = pl:getChildByName("tf_nickname")

	self.tf_id = pl:getChildByName("tf_id")
	self.tf_alipay = pl:getChildByName("tf_alipay")
	self.tf_cardnu = pl:getChildByName("tf_cardnu")

	self.btn_head = pl:getChildByName("btn_head")
	self.atlas_money = pl:getChildByName("atlas_money")
	self.atlas_bank = pl:getChildByName("atlas_bank")
	
	self.txt_lv = pl:getChildByName("levebgsp"):getChildByName("txt_lv")
	self.txt_versiontip = root:getChildByName("txt_versiontip")


	ExternalFun.FixCenterPosY(self.txt_versiontip,nil,nil,true)


	self.btn_modifyName = pl:getChildByName("btn_modyname")
	self.btn_copyId = pl:getChildByName("btn_cpyid")
	self.btn_bindAlipay = pl:getChildByName("btn_bindalipay")
	self.btn_bindCard = pl:getChildByName("btn_bindcard")
	self.btn_switchCount = pl:getChildByName("btn_switchcount") 
	self.btn_register = pl:getChildByName("btn_register")
	self.btn_close = root:getChildByName("closebt")
	
	self.cb_music = root:getChildByName("cb_music")
	self.cb_sound = root:getChildByName("cb_sound")
	self.cleargame = pl:getChildByName("btn_clear")
	self.ft_phone = pl:getChildByName("tf_phone")
	self.cleargame:setVisible(false)
	self.cb_music:addTouchEventListener(btnCallback)
	self.cb_sound:addTouchEventListener(btnCallback)

	self.img_head = pl:getChildByName("Image_1")
	self.headbt = self.img_head:getChildByName("head_bt")
	local nickchangecout = tonumber(GlobalUserItem.nickchangecount) or 0
	if nickchangecout > 0 then
		self.btn_modifyName:setVisible(false)
	else
		self.btn_modifyName:setVisible(true)
	end
	self.btn_modifyName:addTouchEventListener(btnCallback)
	self.btn_copyId:addTouchEventListener(btnCallback)
	self.btn_bindAlipay:addTouchEventListener(btnCallback)
	self.btn_bindCard:addTouchEventListener(btnCallback)
	self.btn_switchCount:addTouchEventListener(btnCallback)
	self.btn_register:addTouchEventListener(btnCallback)
	self.btn_close:addTouchEventListener(btnCallback)
	self.cleargame:addTouchEventListener(btnCallback)
	self.btn_head:addTouchEventListener(btnCallback)
	self.headbt:addTouchEventListener(btnCallback)
	self:hideChangeKindof()
end

function UserInfoLayer:hideChangeKindof()
	if GlobalUserItem.onlyShowLand or GlobalUserItem.safeChannle then
		self.tf_alipay:setVisible(false)
		self.tf_cardnu:setVisible(false)
		self.btn_bindAlipay:setVisible(false)
		self.btn_bindCard:setVisible(false)
		self.panelLayout:setBackGroundImage("userinfo/di_nochange.png")
	else
		self.tf_alipay:setVisible(true)
		self.tf_cardnu:setVisible(true)
		self.btn_bindAlipay:setVisible(true)
		self.btn_bindCard:setVisible(true)
		self.panelLayout:setBackGroundImage("userinfo/dizi.png")
	end
	
end
function UserInfoLayer:init()
	local addstr = appdf.channelId == 100 and "100 ios \n"  or ""
	local localver = cc.UserDefault:getInstance():getIntegerForKey("extra_command_version", 1)
	-- if appdf.channelId < 20 then
	-- 	self.txt_versiontip:setString(addstr.."当前版本:" .. localver.."."..appdf.BASE_C_RESVERSION.."\n当前渠道:"..appdf.channelId
	-- 	.."\n ip:"..appdf.clientSocket._szServerUrl)
	-- else
		self.txt_versiontip:setString(addstr.."当前版本:" .. localver.."."..appdf.BASE_C_RESVERSION
		.."."..appdf.channelId..(appdf.isTest and "-test" or "")..(appdf.isTest and "\n ip:"..appdf.clientSocket._szServerUrl or ""))
	-- end
	self.tf_nick:setString(GlobalUserItem.szNickName)
	self.tf_id:setString(GlobalUserItem.dwUserID)
	utils:LabelSetString(self.tf_cardnu,self:limitAcountLen(GlobalUserItem.bankid),"暂未绑定银行卡")
	utils:LabelSetString(self.tf_alipay,self:limitAcountLen( GlobalUserItem.szAliPayAcccount),"暂未绑定支付宝")

	local moneystr = string.gsub( ExternalFun.ChangeScore( GlobalUserItem.lUserScore,2,","),",","/")
	self.atlas_money:setString(moneystr )
	moneystr = string.gsub( ExternalFun.ChangeScore( GlobalUserItem.lUserInsure,2,","),",","/")
	self.atlas_bank:setString(moneystr)

	if GlobalUserItem.accounttype == 1 then
		self.btn_bindAlipay:setVisible(true)
		self.btn_bindCard:setVisible(true)

	end
	if string.len( string.ltrim(string.rtrim(GlobalUserItem.szAliPayAcccount)) ) > 0 then
		self.btn_bindAlipay:setVisible(false)
	end

	if string.len( string.ltrim(string.rtrim(GlobalUserItem.bankid)) ) > 0 then
		self.btn_bindCard:setVisible(false)
	end

	--head pic
	-- local head = HeadSprite:createClipHead(GlobalUserItem, 92)
	-- head:setAnchorPoint(cc.p(0.5,0.5))


	--music
	local bmusic = cc.UserDefault:getInstance():getBoolForKey("vocieable",true)
	self.bmusic = bmusic
	local bsound = cc.UserDefault:getInstance():getBoolForKey("soundable",true)
	self.bsound = bsound
	self:changeNormalSp(self.cb_music,bmusic)
	self:changeNormalSp(self.cb_sound,bsound)

	self.head = HeadSprite:create(HeadSprite.CLIP,GlobalUserItem, 180,nil,"plaza/headfram.png")
	self.head:setPosition(self.img_head:getPosition())
	self.img_head:getParent():addChild(self.head)
	-- local frameFile = nil
	-- local scaleRate = nil
	
	-- scaleRate = 0.75
	-- self.head:enableHeadFrame(true, {_framefile = frameFile, _scaleRate = scaleRate,_posPer = cc.p(0.5,0.5)})
	self:refreshLayer()
end

function UserInfoLayer:refreshLayer()
	local youkeicon = self.head:getChildByName("youkeicon")
	if GlobalUserItem.accounttype == 1 then
		self.btn_register:setVisible(false)
		utils:LabelSetString(self.ft_phone,GlobalUserItem.szAccount,"未绑定手机")
		if youkeicon then
			youkeicon:removeFromParent()
		end
	else
		self.btn_register:setVisible(true)
		local youkeicon = display.newSprite("userinfo/youkeicon.png")
		youkeicon:setName("youkeicon")
		youkeicon:setScale(0.5)
		local size = self.head:getContentSize()
		youkeicon:setPosition(size.width-18,size.height-10)
		self.head:addChild(youkeicon,100)
	end
end

function UserInfoLayer:changeNormalSp(btn,bselect)
	if bselect then
		btn:loadTextureNormal("userinfo/opensp.png")
	else
		btn:loadTextureNormal("userinfo/closesp.png")
	end

end
function UserInfoLayer:reSetHeadImg()
	self.head:updateHead(GlobalUserItem)
end

function UserInfoLayer:reSetNickname(newname)
	self.tf_nick:setString(newname)
	self.btn_modifyName:setVisible(false)
	GlobalUserItem.nickchangecount = 1
	GlobalUserItem.szNickName = newname
	self._scene.nickNameText:setString(GlobalUserItem.szNickName)
	-- showToast(self, "修改昵称成功!", 1)
end

function UserInfoLayer:copyId()
	local ret, msg = MultiPlatform:copyToClipboard(GlobalUserItem.dwUserID .. "")
	if ret == true then
		showToast(self, "复制成功!", 1)
	else
		if type(msg) == "string" then
			showToast(self, msg, 1, cc.c3b(250, 0, 0))
		end
	end
end

function UserInfoLayer:bindMoneyInfo(btype)
	if btype == 1 then
		local alipay = AlipayLayer:create(self)
		alipay:addTo(self)
	elseif btype == 2 then
		local bindbank = BindBankLayer:create(self)
		bindbank:addTo(self)
	end
	
end

function UserInfoLayer:reSetBindingInfo(msg)
	if msg.type == 1 then
		utils:LabelSetString(self.tf_alipay,self:limitAcountLen( msg.bindid),"暂未绑定支付宝")
		self.btn_bindAlipay:setVisible(false)
	elseif msg.type == 2 then
		utils:LabelSetString(self.tf_cardnu,self:limitAcountLen( msg.bindid),"暂未绑定银行卡")
		self.btn_bindCard:setVisible(false)
	end

end
--过长的*号显示
function UserInfoLayer:limitAcountLen(str)
	if not str or str == nil or str == "" then
		return ""
	end
	local preStr = string.sub(str,1,4)
	local lastStr = string.sub(str,-4,-1)
	return preStr.."******"..lastStr

end
--修改昵称
function UserInfoLayer:modifyName(newName)
	local name = newName or '新名字....ss'
	local msg = {}
	msg.name = name
	appdf.clientSocket:sendModifyName(msg)
end

--修改头像
----self:modifyFaceId("1")
function UserInfoLayer:modifyFaceId(newFaceId)
	local msg = {}
	msg.faceid = newFaceId
	self._scene._LogonFrame:sendChangeFaceId(msg)
end

function UserInfoLayer:operateMusic(bEnable)
	print("operateMusic")
	GlobalUserItem.setVoiceAble(bEnable)
	if bEnable then
		ExternalFun.playPlazzBackgroudAudio()
	end
end

function UserInfoLayer:operateSound(bEnable)
	print("operateSound")
	-- self:modifyFaceId(2)
	GlobalUserItem.setSoundAble(bEnable)
	--ExternalFun.playPlazzBackgroudAudio()
end

function UserInfoLayer:openModifyLayer()
	local modlayer = ModifyLayer:create(self)
	self:addChild(modlayer)

end

function UserInfoLayer:onButtonClicked(tag, ref)
	if ref == self.btn_modifyName then
		print("btn_modifyName")
		self:openModifyLayer()
	elseif ref == self.btn_copyId then
		print("btn_copyId")
		self:copyId()
	elseif ref == self.btn_bindAlipay then
		if GlobalUserItem.accounttype == 1 then
			self:bindMoneyInfo(1)
		else
			showToast(self, "注册成为正式账号后即可绑定并结算现金！", 2)
		
		end

		
	elseif ref == self.btn_bindCard then
		if GlobalUserItem.accounttype == 1 then
			self:bindMoneyInfo(2)
		else
			showToast(self, "注册成为正式账号后即可绑定并结算现金！", 2)
		
		end
	
	elseif ref == self.btn_switchCount then
        self._scene:releasePublicRes()
        self._scene:ExitClient()
	elseif ref == self.btn_register then
		self._scene:openBindingLayer(yl.SCENE_BINDING)
	elseif ref == self.btn_close then
		print("btn_close")
		self._scene:onKeyBack()
		self._scene:refreshLayer()
	elseif ref == self.cb_music then
		self.bmusic = not self.bmusic
		self:changeNormalSp(self.cb_music,self.bmusic)
		self:operateMusic(self.bmusic)
	elseif ref == self.cb_sound then
		self.bsound = not self.bsound
		self:changeNormalSp(self.cb_sound,self.bsound)
		self:operateSound(self.bsound)
	elseif ref == self.cleargame then
		self:gameClear()
elseif ref == self.btn_head or self.headbt then
		print("----btn_head----")

		local mname = ModifyHead:create(self)
		
		self:addChild(mname)
	end
end
function UserInfoLayer:gameClear()
	if device.platform ~= "windows" then
      
		ExternalFun.cleanGameCache(  )
   end
	os.exit(0)
end
return UserInfoLayer
